import fs from 'node:fs'
import path from 'node:path'

// if file is empty, create a new one
if (!fs.existsSync(path.join(__dirname, 'codeStore.json')))
  fs.writeFileSync(path.join(__dirname, 'codeStore.json'), '{}')

// use map temporarily to store the code, TODO: replace with a database
const initialCodeStore = fs.readFileSync(path.join(__dirname, 'codeStore.json')).toString('utf8')
class CodeStore {
  store: Record<string, string>
  constructor(initialCodeStore: string) {
    this.store = JSON.parse(initialCodeStore)
  }

  get(id: string) {
    return this.store[id]
  }

  set(id: string, code: string) {
    this.store[id] = code
  }
}

export const codeStore = new CodeStore(initialCodeStore)

// Every minute, store the code in the file system
setInterval(() => {
  const code = JSON.stringify(codeStore.store)
  fs.writeFileSync(path.join(__dirname, 'codeStore.json'), code)
}, 60000)
